﻿function Global() { }
Global.AjaxResponseCode = {
    Unkown: 0,
    UnAuthorized: 1,
    Succeed: 2,
    Failed: 3
};

Global.Handler = {
    LoginPage: "/Login.aspx"
};

function ProcessAjaxResult(data, textStatus, success, fail, ajxOptions) {
    if (data == undefined || data == null) {
        alert("Ajax response null.");
    } else if (!data.C) {
        alert("Data struct is incorrect.");
    }
    else if (data.C == Global.AjaxResponseCode.UnAuthorized) {/* 需要登录（cookie超时） */
        if (typeof LoginWindow != 'undefined') {
            LoginWindow.show(function () { if (ajxOptions != undefined && ajxOptions != null && ajxOptions.url) { $.ajax(ajxOptions); } });   //弹出登录框，成功后回调传入函数
        } else {
            var url = top.location.href;
            url = url.substring(url.indexOf("/", 7), url.length);
            top.location.href = Global.Handler.LoginPage + "?ReturnUrl=" + encodeURIComponent(url);
        }
    } else if (data.C == Global.AjaxResponseCode.Succeed) {
        if (success && typeof success == "function") success.call(this, data.R, textStatus); //调用指定的成功处理函数
    } else if (data.C == Global.AjaxResponseCode.Failed) {
        if (fail == undefined)
            alert(data.E); //默认处理
        else if (fail && typeof fail == 'function')
            fail.call(this, data.E, textStatus); //调用指定的错误处理函数
    } else {
        alert("Unknown response code: " + data.C + ".");
    }
}

$.ajaxQuest = function (_type, _url, _async, _callback) {
    $.ajax({
        type: _type,
        url: _url,
        dataType: 'json',
        async: _async,
        success: function (data, textStatus) {
            ProcessAjaxResult(data, textStatus,
              function (data, textStatus) {
                  _callback(data);
              },
              function (err, textStatus) {
                  alert('操作失败');
              },
              this);
        }
    });
}

//表示全局唯一标识符 (GUID)。

function Guid(g) {
    var arr = new Array(); //存放32位数值的数组
    if (typeof (g) == "string") { //如果构造函数的参数为字符串
        InitByString(arr, g);
    }
    else {
        InitByOther(arr);
    }

    //返回一个值，该值指示 Guid 的两个实例是否表示同一个值。
    this.Equals = function (o) {
        if (o && o.IsGuid) {
            return this.ToString() == o.ToString();
        }
        else {
            return false;
        }
    }

    //Guid对象的标记
    this.IsGuid = function () { return true; }

    //返回 Guid 类的此实例值的 String 表示形式。
    this.ToString = function (format) {
        if (typeof (format) == "string") {
            if (format == "N" || format == "D" || format == "B" || format == "P") {
                return ToStringWithFormat(arr, format);
            }
            else {
                return ToStringWithFormat(arr, "D");
            }
        }
        else {
            return ToStringWithFormat(arr, "D");
        }
    }

    //由字符串加载
    function InitByString(arr, g) {
        g = g.replace(/\{|\(|\)|\}|-/g, "");
        g = g.toLowerCase();
        if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {
            InitByOther(arr);
        }
        else {
            for (var i = 0; i < g.length; i++) {
                arr.push(g[i]);
            }
        }
    }

    //由其他类型加载
    function InitByOther(arr) {
        var i = 32;
        while (i--) {
            arr.push("0");
        }
    }

    /*
    根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。
    N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 
    B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} 
    P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) 
    */
    function ToStringWithFormat(arr, format) {
        switch (format) {
            case "N":
                return arr.toString().replace(/,/g, "");
            case "D":
                var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);
                str = str.replace(/,/g, "");
                return str;
            case "B":
                var str = ToStringWithFormat(arr, "D");
                str = "{" + str + "}";
                return str;
            case "P":
                var str = ToStringWithFormat(arr, "D");
                str = "(" + str + ")";
                return str;
            default:
                return new Guid();
        }
    }
}

//Guid 类的默认实例，其值保证均为零。
Guid.Empty = new Guid();

//初始化 Guid 类的一个新实例。
Guid.NewGuid = function () {
    var g = "";
    var i = 32;
    while (i--) {

        g += Math.floor(Math.random() * 16.0).toString(16);

    }
    return new Guid(g);
};
(function ($) {
    $.DateFromObj2String = function (val) {
        if (val == null)
            return null;
        var re = /-?\d+/;
        var m = re.exec(val);
        var d = new Date(parseInt(m[0]));
        return d.format("yyyy-MM-dd hh:mm:ss");
    };
    Date.prototype.format = function (format) //为日期类添加format方法
    {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        if (format == "1-01-01 08:00:00")
            return null;
        return format;
    };

    //根据QueryString参数名称获取值
    $.f_getQueryStringByName = function (name) {
        var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
        if (result == null || result.length < 1) {
            return "";
        }
        return result[1];
    };

    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    },
        s = {
            'array': function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            'number': function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            'object': function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            'string': function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function (a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    $.toJSON = function (v) {
        var f = isNaN(v) ? s[typeof v] : s['number'];
        if (f) return f(v);
    };

    $.parseJSON = function (v, safe) {
        if (safe === undefined) safe = $.parseJSON.safe;
        if (safe && !/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(v))
            return undefined;
        return eval('(' + v + ')');
    };

    $.parseJSON.safe = false;

} (jQuery));